// task_create_add_image_text_page.dart
import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sjx/pages/task/create/task_create_fill_in_vm.dart';
import 'package:sjx/repository/sjx_api.dart';



class TaskCreateAddRequirementPage extends StatefulWidget {
  final TaskCreateFillInViewModel? object;

  const TaskCreateAddRequirementPage({
    super.key,
    this.object,
  });

  @override
  _TaskCreateAddRequirementPageState createState() => _TaskCreateAddRequirementPageState();
}

class _TaskCreateAddRequirementPageState extends State<TaskCreateAddRequirementPage> {
  final TextEditingController _contentController = TextEditingController();
  final List<String> _uploadedImages = [];// 已上传的图片URL
  final List<File> _selectedImages = [];// 新选择的本地图片文件
  bool _isEditing = false;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  void _initializeData() {
    if (widget.object != null) {
      // 编辑模式
      if (widget.object!.taskRequirements != null) {
        _contentController.text = widget.object!.taskRequirements!;
      }
      _uploadedImages.addAll(widget.object!.taskRequirementImages);
      _isEditing = false;
    } else {
      // 新增模式
      _isEditing = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加任务要求'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _onBackPressed,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveData,
          ),
        ],
      ),
      body: _buildBody(),
      bottomNavigationBar: _buildBottomButton(),
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文字说明标题
          _buildSectionTitle('任务要求（必填）'),
          const SizedBox(height: 8),

          // 文字输入框
          _buildContentTextField(),
          const SizedBox(height: 24),

          // 图片说明标题
          _buildSectionTitle('图片说明（最多添加4张，选填）'),
          const SizedBox(height: 8),

          // 图片上传区域
          _buildImageUploadSection(),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(left: 16, top: 8, bottom: 8),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F7FA),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 13,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  Widget _buildContentTextField() {
    return Container(
        padding: const EdgeInsets.only(left: 16, right: 16),
        child: TextField(
          controller: _contentController,
          maxLines: 5,
          minLines: 5,
          decoration: InputDecoration(
            hintText: '请详细描述提交任务结果的要求',
            hintStyle: const TextStyle(fontSize: 14, color: Color(0xFF999999)),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Color(0xFFDDDDDD)), // 这里设置颜色
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Colors.blue), // 聚焦时的颜色
            ),
            contentPadding: const EdgeInsets.all(12),
            filled: true,
            fillColor: Colors.white,
          ),
          onChanged: (value) {
            setState(() {
              _isEditing = true;
            });
          },
        )
    );
  }

  Widget _buildImageUploadSection() {
    final totalImages = _uploadedImages.length + _selectedImages.length;

    return Container(
      padding: const EdgeInsets.only(left: 16, right: 16),
      child: Wrap(
        spacing: 8,
        runSpacing: 8,
        children: [
          // 显示已上传的网络图片
          ..._uploadedImages.asMap().entries.map((entry) {
            final index = entry.key;
            final imageUrl = entry.value;
            return _buildNetworkImageItem(imageUrl, index, isUploaded: true);
          }).toList(),

          // 显示新选择的本地图片
          ..._selectedImages.asMap().entries.map((entry) {
            final index = entry.key;
            final image = entry.value;
            return _buildLocalImageItem(image, index + _uploadedImages.length);
          }).toList(),

          // 添加图片按钮
          if (totalImages < 3)
            GestureDetector(
              onTap: _pickImage,
              child: Container(
                width: 100,
                height: 100,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Icon(Icons.add, size: 40, color: Colors.grey),
              ),
            ),
        ],
      ),
    );
  }


  // 构建网络图片项
  Widget _buildNetworkImageItem(String imageUrl, int index, {bool isUploaded = true}) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: CachedNetworkImage(
            imageUrl: imageUrl,
            width: 100,
            height: 100,
            fit: BoxFit.cover,
            placeholder: (context, url) => Container(
              color: Colors.grey[200],
              child: const Center(child: CircularProgressIndicator(strokeWidth: 2)),
            ),
            errorWidget: (context, url, error) => Container(
              color: Colors.grey[200],
              child: const Icon(Icons.error, color: Colors.red),
            ),
          ),
        ),
        Positioned(
          top: 4,
          right: 4,
          child: GestureDetector(
            onTap: () => _removeImage(index, isUploaded: isUploaded),
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.black54,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.close,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        ),
        if (isUploaded)
          Positioned(
            bottom: 4,
            left: 4,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: BorderRadius.circular(4),
              ),
              child: const Text(
                '已上传',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                ),
              ),
            ),
          ),
      ],
    );
  }

  // 构建本地图片项
  Widget _buildLocalImageItem(File image, int index) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.file(
            image,
            width: 100,
            height: 100,
            fit: BoxFit.cover,
          ),
        ),
        Positioned(
          top: 4,
          right: 4,
          child: GestureDetector(
            onTap: () => _removeImage(index, isUploaded: false),
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.black54,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.close,
                color: Colors.white,
                size: 20,
              ),
            ),
          ),
        ),
        Positioned(
          bottom: 4,
          left: 4,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
            decoration: BoxDecoration(
              color: Colors.blue,
              borderRadius: BorderRadius.circular(4),
            ),
            child: const Text(
              '新添加',
              style: TextStyle(
                color: Colors.white,
                fontSize: 10,
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 移除图片
  Future<void> _removeImage(int index, {bool isUploaded = true}) async {
    setState(() {
      if (isUploaded) {
        // 移除已上传的图片
        _uploadedImages.removeAt(index);
      } else {
        // 移除新选择的图片（需要减去已上传图片的数量来获取正确的索引）
        final localIndex = index - _uploadedImages.length;
        if (localIndex >= 0 && localIndex < _selectedImages.length) {
          _selectedImages.removeAt(localIndex);
        }
      }
      _isEditing = true;
    });
  }

  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey[300]!)),
      ),
      child: ElevatedButton(
        onPressed: _saveData,
        style: ElevatedButton.styleFrom(
          backgroundColor: Theme.of(context).primaryColor,
          minimumSize: const Size(double.infinity, 44),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        child: const Text(
          '确定',
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
      ),
    );
  }

  Future<void> _pickImage() async {
    if (_selectedImages.length >= 3) {
      showToast('最多只能上传3张图片');
      return;
    }

    try {
      final List<XFile>? pickedFiles = await ImagePicker().pickMultiImage(
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );

      if (pickedFiles != null && pickedFiles.isNotEmpty) {
        setState(() {
          int remainingSlots = 3 - _selectedImages.length;
          int filesToAdd = pickedFiles.length > remainingSlots
              ? remainingSlots
              : pickedFiles.length;

          for (int i = 0; i < filesToAdd; i++) {
            _selectedImages.add(File(pickedFiles[i].path));
          }

          if (pickedFiles.length > remainingSlots) {
            showToast('已添加$remainingSlots张图片，最多3张');
          }
        });
      }
    } catch (e) {
      showToast('图片选择错误: ${e.toString()}');
    }
  }

  Future<void> _uploadImages() async {
    setState(() {
      _isLoading = true;
    });

    try {
      for (final imageFile in _selectedImages) {
        final bytes = await imageFile.readAsBytes();
        final base64String = base64Encode(bytes);
        final uploadFileUrl = await SJXApi.instance().uploadImage(base64String);
        _uploadedImages.add(uploadFileUrl);
      }
      _selectedImages.clear(); // 清空已上传的本地图片
    } catch (e) {
      showToast('图片上传失败: ${e.toString()}');
      rethrow;
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _saveData() async {
    if (_contentController.text.isEmpty ||
        _contentController.text == '请详细描述提交任务结果的要求') {
      showToast('请详细描述提交任务结果的要求');
      return;
    }

    // 上传新选择的图片
    if (_selectedImages.isNotEmpty) {
      await _uploadImages();
    }

    // 创建一个新的ViewModel实例并返回
    final updatedViewModel = TaskCreateFillInViewModel(
      taskCategoryStr: widget.object?.taskCategoryStr ?? '',
      taskId: widget.object?.taskId,
    );

    updatedViewModel.taskRequirements = _contentController.text;
    updatedViewModel.setTaskRequirementImages(_uploadedImages);

    Navigator.of(context).pop(updatedViewModel);
  }

  void _onBackPressed() {
    if (_isEditing) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('提示'),
          content: const Text('是否放弃当前编辑？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('放弃'),
            ),
          ],
        ),
      );
    } else {
      Navigator.pop(context);
    }
  }

  @override
  void dispose() {
    _contentController.dispose();
    super.dispose();
  }
}